package com.lagou.controller;

import com.lagou.pojo.Token;
import com.lagou.pojo.User;
import com.lagou.service.TokenMapper;
import com.lagou.service.UserMapper;
import com.netflix.client.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Path;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController {

    private Cookie cookie;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private TokenMapper tokenMapper;

    @RequestMapping(value = "add", method = RequestMethod.POST)
    public Integer addUser(@RequestBody User user) {
        int result = userMapper.insertUser(user);
        return result;

    }

    @RequestMapping(value = "register/{email}/{password}/{code}", method = RequestMethod.GET)
    public Integer register(@PathVariable("email")String email, @PathVariable("password") String password, @PathVariable("code") String code){
        User user = new User();
        user.setName(email);
        int result = userMapper.insertUser(user);

        return result;
    }

    @RequestMapping(value = "login/{email}/{password}", method = RequestMethod.GET)
    public String login(HttpServletResponse response, @PathVariable("email") String email, @PathVariable("password") String password) {

        User user = new User();
        user.setName(email);
        User usr = userMapper.getUser(user);
        if(usr == null) {
            return "false";
        }

        String token = String.valueOf(UUID.randomUUID());
        cookie = new Cookie("token", token);
        response.addCookie(cookie);
        //token写入数据库
        Token tokens = new Token();
        tokens.setEmail(email);
        tokens.setToken(token);
        tokenMapper.addToken(tokens);

        return "true";
    }


}
